<?php

use App\Helpers\Bing;
use App\Models\Picture;

/**
 * 格式化API返回内容
 * @param null $data
 * @param int $code
 * @return array
 */
function rsp($data = null, $code = 20000)
{
    $errors = config('errors');
    if ($code != 20000 && !$data) {
        $data = $errors[$code];
    }
    return [
        'code' => $code,
        'data' => $data
    ];
}

function debugger($content, $filename = null, $line = null)
{
    logger('********************************** START ******************************************');
    logger('当前文件为：' . $filename);
    logger('当前代码执行位置为：' . $line);
    logger('****** 详细日志内容如下： ******');
    logger($content);
    logger('********************************** END ******************************************');
}

function downloadBing()
{
    debugger('必应壁纸下载', __FILE__, __LINE__);
    $b = new Bing();
    $items = $b->getLatestPicCN();
    foreach ($items as $item) {
        $url = $item['url'];
        $path = $b->download($url);
        $date = $item['enddate'];
        $date = substr_replace($date, '-', 6, 0);
        $date = substr_replace($date, '-', 4, 0);
        $bing = Picture::where('hsh', $item['hsh'])->first();
        if (empty($bing)) {
            $bing = new Picture();
            $bing['outside_url'] = $url;
            $bing['remark'] = $date;
            $bing['title'] = $item['copyright'];
            $bing['hsh'] = $item['hsh'];
            $bing['local_url'] = $path;
            $bing->save();
        }
    }
    return $items;
}
